(function(w) {
	if(window.FastClick)
		FastClick.attach(document.body);

	Date.prototype.format = function(fmt) {
		var o = {
			"M+": this.getMonth() + 1, //月份 
			"d+": this.getDate(), //日 
			"h+": this.getHours(), //小时 
			"m+": this.getMinutes(), //分 
			"s+": this.getSeconds(), //秒 
			"q+": Math.floor((this.getMonth() + 3) / 3), //季度 
			"S": this.getMilliseconds() //毫秒 
		};
		if(/(y+)/i.test(fmt)) fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
		for(var k in o)
			if(new RegExp("(" + k + ")").test(fmt)) fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
		return fmt;
	}

	var Util = {
		getUrlParam: function(name) {
			var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
			var r = window.location.search.substr(1).match(reg);
			if(r != null) return unescape(r[2]);
			return null;
		},
		stateText: ['待派单', '待整改', '已整改', '已通过'],
		stateClass: ['', 'mui-btn-danger', 'mui-btn-primary', 'mui-btn-success'],
		dataState: {
			normal: 0, //从服务器下载的状态
			modify: 1, //本地更改后的状态
			add: 2, //本地添加后的状态
			remove: 3 //本地删除后的状态
		},
		houseState: { //房屋状态
			not_check: 1, //待检查
			not_fix: 2, //待整改
			fixed: 3, //已整改
			passed: 4 //已通过
		},
		problemState: { //问题状态
			not_send: 1, //待派送
			not_fix: 2, //待整改
			fixed: 3, //已整改
			passed: 4, //已通过
			discarded: 5, //已作废
		},
		imageState: { //图片状态
			problemAdd: 1, //新增
			recheckAdd: 2, //复验新增，未通过
			recheckPass: 3 //复验通过
		},
		isWIFI: function() {
			return plus.networkinfo.getCurrentType() == plus.networkinfo.CONNECTION_WIFI;
		},
		/**
		 * 获取相机照片
		 */
		getCameraImage: function(view) {
			var _this = this;
			return new Promise(function(resolve, reject) {
				var c = plus.camera.getCamera();
				c.captureImage(function(path) {
					plus.io.resolveLocalFileSystemURL(path, function(entry) {
						console.log(entry.fullPath);
						_this.goImageEdit({
							src: entry.fullPath,
							replace: true,
							view: view
						})
					}, function(e) {
						console.log("读取拍照文件错误：" + e.message);
					});
				}, function(s) {
					console.log("error" + s);
				}, {
					filename: '_doc/camera/' + UUID.generate() + '.jpg'
				})
			})
		},
		/**
		 * 获取相册照片
		 */
		getGalleryImage: function(view) {
			var _this = this;
			return new Promise(function(resolve, reject) {
				plus.gallery.pick(function(path) {
					//					console.log(path);
					plus.io.resolveLocalFileSystemURL('_doc/', function(docEntry) {
						//获取目录，没有则创建
						docEntry.getDirectory('camera', {
							create: true
						}, function(dir) {
							plus.io.resolveLocalFileSystemURL(path, function(entry) {
								console.log(path);
								_this.goImageEdit({
									src: path,
									view: view
								})
							})
						}, function(e) {
							console.log('打开camera目录失败');
						})

					}, function(e) {
						console.log("读取照片文件错误：" + e.message);
					});
				}, function(a) {}, {
					filter: "image"
				})
			})
		},
		/**
		 * 压缩图片
		 * @param {Object} obj
		 */
		compressImage: function(obj) {
			return new Promise(function(resolve, reject) {
				var option = {
					src: obj.src,
					dst: obj.dest ? obj.dest : obj.src,
					quality: 30,
					overwrite: true,
					width: '50%',
					height: '50%'
				};
				if(obj.rotate) option.rotate = obj.rotate;
				console.log(JSON.stringify(option));
				plus.zip.compressImage(option, function() {
					resolve(obj.src);
					console.log('压缩图片 成功 ' + obj.src);
				}, function(e) {
					reject('压缩图片失败 ' + obj.src);
					console.log('压缩图片失败 ' + obj.src + ' error: ' + e.message);
				})
			})
		},
		/**
		 * 获取图片旋转角度
		 */
		getImageOrientation: function(url) {
			if(plus.os.name == 'iOS')
				return Promise.resolve(0);

			if(!window.EXIF)
				return Promise.reject('exif not exist');

			return new Promise(function(resolve, reject) {
				var img = document.createElement('img');
				img.src = url;
				img.style.width = 0;
				img.style.height = 0;
				document.body.appendChild(img);
				img.onload = function() {
					var time = Date.now();
					EXIF.getData(img, function() {
						var ort = EXIF.getTag(this, 'Orientation');
						var deg = 0;
						console.log(ort);
						switch(ort) {
							case 1: //0
								break;
							case 3: //180
								deg = 180;
								break;
							case 6: //90
								deg = 90
								break;
							case 8: //270
								deg = 270;
								break;
							default:
								break;
						}
						img.remove();
						resolve(deg);
					})
				}
				img.onerror = function() {
					console.log('加载图片失败');
					reject('加载图片失败');
					img.remove();
				}
			})
		},
		/**
		 * 提示，判断是否是在app中
		 * @param {Object} msg
		 */
		toast: function(msg) {
			if(window.plus)
				plus.nativeUI.toast(msg, {
					'verticalAlign': 'bottom'
				})
			else
				mui.toast(msg);
		},
		/**
		 * 下载图片
		 * 
		 * @param {String} prefix	服务器图片地址前缀
		 * @param {String} filename 图片名称/相对路径
		 */
		downloadImage: function(url, file) {
			var _this = this;
			return new Promise(function(resolve, reject) {
				//				console.log('下载图片 ' + file)
				_this.imageExistLocal('_doc/camera/' + file).then(function(exist) {
					if(!exist) {
						var dtask = plus.downloader.createDownload(url, {
							method: 'POST',
							data: "imageName=" + file,
							filename: '_doc/camera/' + file,
							retry: 0,
							timeout: 10
						}, function(d, status) {
							if(status == 200) { // 下载完成
								resolve();
//								console.log("下载图片 成功: " + d.filename);
							} else {
								reject()
								console.log("下载图片 失败: " + status);
							}
						});
						dtask.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded'); //ios 默认为text/html,必须设置。20170710
						dtask.start();
					}else{
						resolve();
					}
				})
			});
		},
		/**
		 * 上传图片
		 * @param {String} url	接口地址
		 * @param {String} file 图片的相对地址
		 */
		uploadImage: function(url, file) {
			return new Promise(function(resolve, reject) {
				var task = plus.uploader.createUpload(url, {},
					function(t, status) {
						if(status == 200) { // 上传完成
							resolve();
							console.log("上传图片成功: " + t.url);
						} else {
							reject();
							console.log("上传图片失败: " + status);
						}
					}
				);
				task.addFile(file, {
					key: 'file'
				});
				task.start();
			});
		},
		showNativeWaiting: function(waitingText) {
			if(!window.plus)
				return;

			plus.nativeUI.showWaiting(waitingText || '', {
				back: 'none',
				width: 120,
				height: 120,
				loading: {
					height: 40
				}
			});
		},
		goImageEdit: function(data) {
			mui.openWindow({
				id: 'image_edit.html',
				url: 'image_edit.html',
				extras: data,
				show: {
					aniShow: false
				},
				waiting: {
					autoShow: false
				}
			})
		},
		/**
		 * 检测本地图片是否存在
		 * @param {String} url
		 */
		imageExistLocal: function(url) {
			return new Promise(function(resolve, reject) {
				plus.io.resolveLocalFileSystemURL(url, function(entry) {
					resolve(true);
				}, function(e) {
					resolve(false);
				});
			})
		}
	};

	w.Util = Util;
})(window);